package com.hainiu.cat.interview.juc;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * create by biji.zhao on 2021/7/2
 */
public class AtomicStampedReferenceTest {

    private static AtomicStampedReference<Integer> atomicStampedRef = new AtomicStampedReference<>(1, 0);
    public static void main(String[] args){
        new Thread(() -> {
            System.out.println("操作线程" + Thread.currentThread() +",初始值 a = " + atomicStampedRef.getReference());
            // 先获取当前标识别
            int stamp = atomicStampedRef.getStamp();
            try {
                // 以便让干扰线程执行
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 此时expectedReference未发生改变，但是stamp已经被修改了,所以CAS失败
            boolean isCASSuccess = atomicStampedRef.compareAndSet(1,2, stamp,stamp + 1);
            System.out.println("操作线程" + Thread.currentThread() +" ,CAS操作结果: " + isCASSuccess);
        },"主操作线程").start();
        new Thread(() -> {
            try {
                // 确保thread-main 优先执行
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 先将值改为2，又将值改为1
            atomicStampedRef.compareAndSet(1,2, atomicStampedRef.getStamp(),atomicStampedRef.getStamp() + 1);
            System.out.println("操作线程" + Thread.currentThread() +",【increment】 ,值 = "+ atomicStampedRef.getReference());
            atomicStampedRef.compareAndSet(2,1,atomicStampedRef.getStamp(),atomicStampedRef.getStamp() +1);
            System.out.println("操作线程" + Thread.currentThread() +",【decrement】 ,值 = "+ atomicStampedRef.getReference());
        },"干扰线程").start();
    }
}
